package org.devocean.groupbuying.service.security;

import java.util.ArrayList;
import java.util.Collection;
import org.devocean.groupbuying.dao.UserDao;
import org.devocean.groupbuying.domain.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UserDao dao;

	@Transactional(readOnly = true)
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		UserDetails userDetails = null;
		org.devocean.groupbuying.domain.User userEntity = dao
				.findUser(username);
		if (userEntity == null)
			throw new UsernameNotFoundException("user not found");

		return buildUserFromUserEntity(userEntity);
	}

	public User buildUserFromUserEntity(
			org.devocean.groupbuying.domain.User userEntity) {

		String principalName = String.valueOf(userEntity.getUserID());
		String password = userEntity.getPassword();
		boolean enabled = userEntity.getEnabled();
		boolean accountNonExpired = userEntity.getEnabled();
		boolean credentialsNonExpired = userEntity.getEnabled();
		boolean accountNonLocked = userEntity.getEnabled();

		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (Role role : userEntity.getUserRoles()) {
			authorities.add(new GrantedAuthorityImpl(role.getAuthority()));
		}

		User user = new org.springframework.security.core.userdetails.User(
				principalName, password, enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked, authorities);
		return user;
	}
}
